$(function () {
    var query = {},
        fields = 'id|userName|password|name|gender|phone|comid|depid|qq', fields_ = 'id|name',
        user_roles = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        $log = $('.btn-log'),
        $updatePasswd = $('.btn-update-passwd'),
        $distRole = $('.btn-dist-role'),
        $dimission = $('.btn-dimission'),
        $return = $('.btn-return'),
        strHtml = $('#form-template').html();
    updatePasswordHtml = $('#form-update-password-template').html();
    distRoleHtml = $('#form-dist-role-template').html();
    var btns = [$update, $delete, $updatePasswd, $distRole, $dimission, $return, $log];
    var config = {
        query: '/user/query?',//分页查询URL,
        query_com: '/com/query?',//分页查询URL,
        query_dep: '/dep/query?',//分页查询URL,
        query_role: '/role/list?',//分页查询URL,
        create: '/user/create',//create,
        update: '/user/update',
        role_update: '/user/role_update',
        get_user_role: '/user/get_user_role',
        'delete': '/user/delete',
        off: '/user/off',
        on: '/user/on',
    };

    var FETCH_ = {
        COMS: {DATA: '', STATUS: false},
        DEPS: {DATA: '', STATUS: false},
        ROLES: {DATA: '', STATUS: false}
    };

    function getDataByUrl(url, DATA_) {

        var dtd = $.Deferred();
        if (!FETCH_[DATA_]) { // undefined
            FETCH_[DATA_] = {DATA: '', STATUS: false};
        }
        if (!!FETCH_[DATA_].DATA) { // 直接返回当前数据
            dtd.resolve(FETCH_[DATA_].DATA);
        } else {
            if (!FETCH_[DATA_].STATUS) {
                FETCH_[DATA_].STATUS = true;
                $.get(url, function (data) {
                    if (data.code == 200) {
                        FETCH_[DATA_].DATA = data.list;
                        dtd.resolve(FETCH_[DATA_].DATA);
                    } else {
                        dtd.reject(data.error)
                    }
                    FETCH_[DATA_].STATUS = false;
                });
            } else {
                //暂行解决方法
                var inter = setInterval(function () {
                    if (!!FETCH_[DATA_].STATUS) {
                        dtd.resolve(FETCH_[DATA_].DATA);
                        clearInterval(inter);
                    }
                }, 100);
            }
        }
        return dtd.promise();
    }

    function search(obj, isForce) {
        var query_ = {};

        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_,query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        };
        query = query_;query.timestamp = Date.now(); 
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        $.get(config.query + arg.join('&'), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: [
                    {name: 'name', _sort: 'name', label: '姓名', enableSort: true, enableSearch: true},
                    {name: 'userName', _sort: 'user_name', label: '用户名', enableSort: true, enableSearch: true},
                    {
                        name: 'gender', _sort: 'gender', label: '性别', filter: function (item) {
                        return ((item.gender == 1) ? '男' : (item.gender == 0 ? '女' : '-'));
                    }
                    },
                    {name: 'jobNum', _sort: 'job_num', label: '工号'},
                    {name: 'qq', _sort: 'qq', label: 'QQ'},
                    {name: 'phone', _sort: 'phone', label: '手机'},
                    {
                        name: 'status', _sort: 'status', label: '状态', filter: function (item) {
                        return (item.status == 1 ? '在职' : (item.status == 0 ? '<span class="label label-danger">离职</span>' : (item.status == 3 ? '删除' : '')) );
                    }
                    },
                    {name: 'comName', _sort: 'com_name', label: '公司'},
                    {name: 'depName', _sort: 'dep_name', label: '部门'},
                ],
                data: res.list || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }

    onClick($update, function () {
        var $current = $(this).data('json'), self = this,
            $modal = _alert({
                title: '修改用户"' + $current.name + '"',
                body: ejs.render(strHtml, $current),
                shown: function () {
                    initCaseCade($current.comid, $current.depid, true);
                    validate($modal);
                }
            });
    });
    $delete.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        $(self).button('loading');
        if (confirm('确认删除"' + $(this).data('json').name + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                $(self).button('reset');
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {
            $(self).button('reset');
        }
    });
    $create.unbind('click').on('click', function () {
        var $modal = _alert({
            title: '新建用户(默认密码123456)',
            body: ejs.render(strHtml, {name: ''}),
            shown: function () {
                initCaseCade();
                validate($modal);
            }
        })
    });
    onClick($log, function () {
        var $current = $(this).data('json');
        window.location = './../../log/log.html?id=' + $current.id + '&type=user';
    });
    $updatePasswd.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        var $modal = _alert({
            title: '修改用户"' + $(this).data('json').name + '"密码',
            body: ejs.render(updatePasswordHtml, {id: $current.id}),
            shown: function () {
                validateUpdatePassword($modal);
            }
        })
    });
    $distRole.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        $.get(config.get_user_role + '?id=' + $current.id, function (data) {
            data.list.map(function (item) {
                $('.role-list input[value=' + item.id + ']').attr('checked', true).prop('checked', true);
            });
        });
        $.when(getDataByUrl(config.query_role, 'ROLES'))
            .then(function (roles) {
                var $modal = _alert({
                    title: '指派用户"' + $current.name + '"角色',
                    body: ejs.render(distRoleHtml, {id: $current.id, name_: $current.name, roles: roles}),
                    shown: function () {
                        $.when(getDataByUrl(config.get_user_role + '?id=' + $current.id, $current.id))
                            .then(function (roles_) {
                                roles_.map(function (item) {
                                    $('.role-list input[value=' + item.id + ']').attr('checked', true).prop('checked', true);
                                });
                                validatedistRoleForm($modal, roles_);
                            })
                            .fail(function (e) {
                                console.log('error occurs when fetch some one user roles : ' + e)
                            });

                    }
                })
            })
            .fail(function (e) {
                console.log('error occurs when fetch user roles : ' + e)
            });
    });
    $dimission.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        if (confirm('确认离职用户"' + $current.name + '"？')) {
            $.post(config.off, {id: $current.id}, function (xhr, data) {
                if (xhr.code == 200) {
                    search({}, true);
                    alert('操作成功!')
                } else {
                    alert(xhr.error);
                }
            });
        }
    });
    $return.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        if (confirm('确认恢复用户"' + $current.name + '"？')) {
            $.post(config.on, {id: $current.id}, function (xhr, data) {
                if (xhr.code == 200) {
                    search({}, true);
                    alert('操作成功!')
                } else {
                    alert(xhr.error);
                }
            });
        }
    });
    /**
     * 初始化单位-部门级联
     */
    function initCaseCade(comid, depid, isDisabled) {
        $.when(
            getDataByUrl(config.query_com, 'COMS'),
            getDataByUrl(config.query_dep, 'DEPS')
        ).then(function (coms, deps) {
            var $comid = $('[name=comid]');
            coms.forEach(function (item) {
                $comid.append('<option value="' + item.id + '">' + item.name + '</option>')
            });
            $comid.off('change').on('change', function () {
                var $it = $(this).val();
                initDep($it);

            });
            comid = comid || $comid.val();
            if (comid) {
                $comid.val(comid);
                initDep(comid, depid);
            }

            if (isDisabled) {
                disableBtn($('[name=comid]'));
                // disableBtn($('[name=depid]')); // 暂时允许能够修改用户的归输部门信息 2017.08.16
            }
            function initDep($it, depid) {
                var $dep = $('[name=depid]');
                $dep.html('');
                var depsByGroup = _.groupBy(deps, 'comid');
                if (depsByGroup[$it]) {
                    depsByGroup[$it].forEach(function (itemDep) {
                        if (depid) {
                            $dep.append('<option ' + (depid == itemDep.id ? 'selected' : '') + ' value="' + itemDep.id + '">' + itemDep.name + '</option>')
                        } else {
                            $dep.append('<option value="' + itemDep.id + '">' + itemDep.name + '</option>')
                        }

                    })
                }
            }
        });

    }

    function destroyBtn() {
        btns.forEach(function (item) {
            item.data('json', null);
            disableBtn(item);
        });
    }

    function createBtn(_this) {
        btns.forEach(function (item) {
            var $item = $(_this).data('json');
            if ($item.status == 1) {
                if (!item.hasClass('btn-return')) {
                    item.data('json', $item);
                    enableBtn(item);
                }
            } else {
                if (!item.hasClass('btn-dimission')) {
                    item.data('json', $item);
                    enableBtn(item);
                }
            }

        });
    }

    search({},true);
    function validateUpdatePassword(modal) {
        $('#updatePasswordForm')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                password: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '密码不能为空'
                        },
                        stringLength: {
                            min: 6,
                            max: 40,
                            message: '密码长度最少6位，最多40位'
                        },
                    }
                },
                confirmPassword: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '确认密码不能为空'
                        },
                        identical: {
                            field: 'password',
                            message: '确认密码和密码不一致'
                        }
                    },

                },
            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var url = config.update;
            form.password = md5(form.password)
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess('修改成功');
                    search({},true);
                    modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }

    function validatedistRoleForm(modal, roles_) {
        $('#distRoleForm')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                name: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        },
                    }
                },
                roles: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '请选择用户角色'
                        },
                    },
                },
            }
        }))
            .off('success.form.fv.submit')
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            form.rolesChange = [];
            $('.role-list [type=checkbox]:checked').each(function (index, item) {
                form.rolesChange.push($.trim($(item).closest('label').text()));
            });
            var origin = roles_.map(function (item, index) {
                return item.roleName;
            });
            form.logs = origin.join(',') + "变更为" + form.rolesChange.join(',');
            form.rolesChange = '';
            var url = config.role_update;
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess('提交成功');
                    search({},true);
                    modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }

    function validate(modal) {
        console.log('122181');
        $('#registrationForm')
            .formValidation('destroy')
            .formValidation($.extend({}, VALIDATION_SETTING, {
                fields: {
                    name: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '姓名'
                            },
                            stringLength: {
                                min: 2,
                                max: 40,
                                message: '姓名长度最少2位，最多10位'
                            },
                        }
                    },
                    userName: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '必填'
                            },
                        }
                    },
                    phone: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '必填'
                            },
                            phone: {
                                country: 'CN',
                                // message:'请输入正确电话'
                            }
                        }
                    },
                    gender: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '必填'
                            },
                        }
                    },
                    qq: {
                        row: '.col-xs-7',
                        validators: {}
                    },
                    comid: {
                        row: '.col-xs-4',
                        validators: {
                            notEmpty: {
                                message: '必填'
                            },
                        }
                    },
                    depid: {
                        row: '.col-xs-3',
                        validators: {
                            notEmpty: {
                                message: '必填'
                            },
                        }
                    },
                }
            }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var url = '';
            if (form.id) { // is update?
                url = config.update;
            } else {
                url = config.create;
                delete form.id;
                form.password = md5('123456');
            }
            if (form.name) {
                form.name = form.name.trim();
            }
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess(form.id ? '保存成功' : '创建成功!');
                    search({},true);
                    modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }
});